package com.jokerku.mini.schedule.loadbalance.impl;

import com.jokerku.mini.schedule.loadbalance.LoadBalance;
import com.jokerku.mini.schedule.loadbalance.LoadBalanceStrategy;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: guzq
 * @CreateTime: 2023/06/14 17:05
 * @Description: 轮询负载均衡
 * @Version: 1.0
 */
public class PollLoadBalance implements LoadBalance {

    private final AtomicInteger frequency = new AtomicInteger(0);

    @Override
    public String getDispatchIp(List<String> ipList) {
        if (CollectionUtils.isEmpty(ipList)) {
            throw new RuntimeException("Ip list cannot be empty");
        }

        int index = Math.abs(frequency.incrementAndGet());

        return ipList.get(index % ipList.size());
    }

    @Override
    public LoadBalanceStrategy getStrategy() {
        return LoadBalanceStrategy.Poll;
    }
}
